package cn.jolyoulu.common.web.security.interceptors;

import cn.jolyoulu.common.web.excption.GlobalException;
import cn.jolyoulu.common.web.security.entity.LoginUser;
import cn.jolyoulu.common.web.security.enums.SecurityExpType;
import cn.jolyoulu.common.web.security.permission.RequiresLogin;
import cn.jolyoulu.common.web.security.service.TokenService;
import cn.jolyoulu.common.web.security.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * @Author LuZhouJin
 * @Date 2023/3/17
 * 用户登录校验
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //获取请求的方法
        HandlerMethod h = (HandlerMethod) handler;
        RequiresLogin permission = h.getMethodAnnotation(RequiresLogin.class);
        if (Objects.isNull(permission)){
            //如果没有定义RequiresLogin注解，不用做登录校验
            return true;
        }
        String token = SecurityUtils.getToken(request);
        if(StringUtils.isBlank(token)){
            throw new GlobalException(SecurityExpType.TOKEN_NOT_EXIST.code(),"请重新登录");
        }
        LoginUser<?> loginUser = SecurityUtils.getLoginUser();
        if (Objects.isNull(loginUser)){
            throw new GlobalException(SecurityExpType.TOKEN_NOT_EXIST.code(),"您的账号已在其他设备登录");
        }
        //比对token，并且自动续期
        tokenService.verifyToken(loginUser);
        return true;
    }
}
